<template>
    <div class="login">
        <div class="logo">
            <img src="../../assets/image/logo@2x.png" alt="" />
        </div>
        <el-card class="ipt">
            <div class="title">
                <span :class="{ activetitle: typeflag === 0 }" @click="chengeloginfn(0)">快捷登录</span><span
                    :class="{ activetitle: typeflag === 1 }" @click="chengeloginfn(1)">密码登录</span>
            </div>
            <div class="line"></div>
            <div class="form">
                <div>
                    <input class="log_ipt" v-model="name" placeholder="请输入手机号" />
                </div>
                <div v-if="typeflag === 0">
                    <input class="log_ipt" v-model="phonecode" placeholder="请输入短信验证码" @keydown.enter="login" />
                    <span class="pointer" v-show="!showsecond" @click="openimgcodetc">{{
                        phonetext
                    }}</span>
                    <span class="pointer" v-show="showsecond">{{ second }}秒重新获取</span>
                </div>
                <div v-if="typeflag === 1">
                    <input class="log_ipt" v-model="password" placeholder="请输入密码" :type="type" />
                    <el-icon style="margin-right: 20px" @click="openeye" v-show="type === 'password'">
                        <Hide />
                    </el-icon>
                    <el-icon style="margin-right: 20px" @click="hideeye" v-show="type === 'text'">
                        <View />
                    </el-icon>
                </div>
                <div v-if="typeflag === 1">
                    <input class="log_ipt" v-model="imgcode" placeholder="请输入图形验证码" @keydown.enter="login" />
                    <img @click="changeimg" crossorigin="anonymous" :src="img" alt="" />
                </div>
                <el-checkbox v-if="typeflag === 1" v-model="keepPwd">记住密码</el-checkbox>
            </div>
            <div class="log_button my_btn" @click="login">立即登录</div>
        </el-card>
        <el-card class="cipt" v-if="showimgcode">
            <div class="top">
                <div></div>
                <div style="font-size: 25px; margin-left: 120px; cursor: pointer" @click="close">
                    x
                </div>
            </div>
            <div>
                <v-verify @successcode="success"></v-verify>
            </div>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import vVerify from '../../components/slideVerify/slideVerify.vue'
import { ref, onMounted, reactive, getCurrentInstance } from 'vue'
const {
    emit,
    appContext: {
        app: {
            config: { globalProperties },
        },
    },
} = getCurrentInstance()
import {
    getloginimg,
    userlogin,
    getuserinfoapi,
    getrouter,
    getlogincodeapi,
} from '../../api/api'
import { ElMessage } from 'element-plus'
import { Base64 } from 'js-base64'
import type { loginimg } from '../../typescript/interface'
import router from '../../router'
import { useStore } from '../../store/index'
const showsecond = ref(false)
const store = useStore()
const showimgcode = ref(false)
const img = ref<string>('')
const loginimgmsg = reactive({})
const keepPwd = ref(false)
import { useRouterStore } from '@/store/routerInfo/index.ts'

const routerStore = useRouterStore()

const chengeloginfn = (i: any) => {
    typeflag.value = i
    phonecode.value = ''
    name.value = ''
    password.value = ''
    imgcode.value = ''
    if (i === 1) {
        if (localStorage.getItem('keepPwd') === '1') {
            keepPwd.value = true
            password.value = localStorage.getItem('password')
            name.value = localStorage.getItem('name')
        } else {
            keepPwd.value = false
        }
        getimg()
    }
}
const typeflag = ref(0)
const success = (val: any) => {
    console.log(val)
    if (val) {
        let code = '' //声明一个空的字符串值用于后面赋值
        const codeLength = 6 //随机密码的长度
        const random = [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2] //随机数的取值范围
        for (let i = 0; i < codeLength; i++) {
            //循环遍历codeLength，值是几，就循环几次
            const index = Math.floor(Math.random() * 10)
            code += random[index] //根据索引取得随机数加到code上
        }
        showimgcode.value = false
        showsecond.value = true
        const time = setInterval(() => {
            second.value--
            if (second.value <= 0) {
                second.value = 60
                clearInterval(time)
                showsecond.value = false
            }
        }, 1000)
        getlogincodeapi({
            passCard: code,
            phone: name.value,
        }).then((res: any) => {
            console.log(res)
        })
    }
}
const second = ref(60)
const close = () => {
    showimgcode.value = false
}
const openimgcodetc = () => {
    var reg = /^(?:(?:\+|00)86)?1\d{10}$/
    if (reg.test(name.value)) {
        console.log(111)
        showimgcode.value = true
    } else {
        console.log(222)
        ElMessage({
            message: '请输入正确手机号码',
            type: 'warning',
        })
    }
}
onMounted(() => {
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('userid')
    // localStorage.clear()
})
const iptlogin = (e: any) => {
    console.log(e)
}
const hideeye = () => {
    type.value = 'password'
}
const openeye = () => {
    type.value = 'text'
}
const type = ref('password')
// 获取验证码图片方法
const getimg = () => {
    getloginimg().then((res) => {
        // console.log(res);
        img.value = 'data:image/png;base64,' + res.img
        uuid.value = res.uuid
    })
}

// 定义获取验证码按钮文字
const phonetext = ref('获取验证码')
// 定义手机号
// const phone = ref<string>("");
// 定义图形验证码
const imgcode = ref<string>('')
// 定义手机验证码
const phonecode = ref<string>('')
// 定义账号
const name = ref('')
// 定义密码
const password = ref('')
const uuid = ref('')
// 点击登录
const login = () => {
    let obj: any = null
    console.log('调用登录接口')
    if (typeflag.value === 1) {
        if (keepPwd.value) {
            localStorage.setItem('password', password.value)
            localStorage.setItem('name', name.value)
            localStorage.setItem('keepPwd', keepPwd.value ? '1' : '0')
        }else{
            localStorage.setItem('name', '')
            localStorage.setItem('password', '')
            localStorage.setItem('keepPwd', keepPwd.value ? '1' : '0')
        }
        obj = {
            username: name.value,
            password: password.value,
            code: imgcode.value,
            uuid: uuid.value,
            platFrom: 2, //crm平台标识 ！
        }
    } else {
        obj = {
            loginType: 1,
            username: name.value,
            verifyCode: phonecode.value,
            platFrom: 2, //crm平台标识 ！
        }
    }
    userlogin(obj)
        .then((res: any) => {
            console.log(res)
            if (res.code == 200) {
                router.push('/')
                ElMessage({
                    message: res.msg,
                    type: 'success',
                })
                // getrouter().then((res: any) => {
                // console.log(res);
                // var arr: any = [];
                // res.forEach((ele: any, index: any) => {
                //   arr.push(...ele.children);
                // });
                // const arr2 = arr.map((ele: any, index: number) => {
                //   return {
                //     path: "/" + ele.path,
                //     name: ele.path,
                //     meta: {
                //       requireAuth: true, // 该路由项需要权限校验
                //     },
                //     component: ele.path,
                //   };
                // });
                // store.addrouter(arr2);
                // store.addrouter(arr);
                // sessionStorage.setItem("router", JSON.stringify(arr2));
                // console.log(arr2);
                // });
                getuserinfoapi().then((res: any) => {
                    console.log(res, 'yfusfuyidsgiuoesiur')
                    sessionStorage.setItem('userid', res.user.userId)
                    sessionStorage.setItem('img', res.user.avatar)
                    sessionStorage.setItem('name', res.user.nickName)
                    sessionStorage.setItem('isGrpLead', res.user.isGrpLead)
                    sessionStorage.setItem('isSupPcAdmin', res.user.isSupPcAdmin)

                    let adminflag: any = null
                    if (res.user.isGrpLead === 1 && res.user.isSupPcAdmin === 0) {
                        adminflag = 1
                    }
                    if (res.user.isGrpLead === 0 && res.user.isSupPcAdmin === 1) {
                        adminflag = 2
                    }
                    if (res.user.isGrpLead === 1 && res.user.isSupPcAdmin === 1) {
                        adminflag = 2
                    }
                    globalProperties.roleflag = adminflag
                })
                sessionStorage.setItem('token', res.token)
                window.location.reload()
            } else {
                ElMessage({
                    message: res.msg,
                    type: 'error',
                })
            }
        })
        .catch(() => {
            imgcode.value = ''
            getloginimg().then((res) => {
                // console.log(res);
                img.value = 'data:image/png;base64,' + res.img
                uuid.value = res.uuid
            })
        })
}
// 点击图片切换
const changeimg = () => {
    getimg()
}
</script>

<style lang="scss" scoped>
.login {
    position: relative;
    box-sizing: border-box;
    padding: 20px;
    width: 100vw;
    height: 100vh;
    background-image: url("../../assets/image/bac.png");
    background-repeat: no-repeat;
    background-size: 100%;
    background-position: 50px, 50px;

    .cipt {
        position: absolute;
        top: 25%;
        left: 50%;
        width: 550px;
        height: 370px;
        border-radius: 20px;
        box-sizing: border-box;
        padding: 10px;

        .cipt::after {
            content: "";
            opacity: 0.5;
            position: absolute;
            background-color: red;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            z-index: 999;
        }

        .top {
            display: flex;
            align-items: center;
            justify-content: space-around;
            margin-bottom: 10px;
        }
    }

    .ipt {
        position: absolute;
        top: 25%;
        left: 50%;
        width: 550px;
        height: 370px;
        background-color: #ffffff;
        border-radius: 20px;
        box-sizing: border-box;
        padding: 10px;

        .title {
            color: rgba(32, 36, 40, 1);
            font-size: 18px;
            display: flex;
            cursor: pointer;
            align-items: center;
            justify-content: space-around;
        }

        .line {
            margin-top: 25px;
            width: 100%;
            height: 2px;
            background-color: rgba(239, 242, 245, 1);
        }

        .form {
            display: flex;
            flex-direction: column;

            div {
                border: 1px solid rgba(234, 234, 239, 1);
                border-radius: 5px;
                height: 40px;
                display: flex;
                margin-top: 20px;
                justify-content: space-between;
                align-items: center;

                img {
                    height: 40px;
                    border-top-right-radius: 5px;
                    border-bottom-right-radius: 5px;
                }

                span {
                    display: block;
                    padding-right: 20px;
                    padding-left: 10px;
                    height: 30px;
                    line-height: 30px;
                    font-size: 14px;
                    border-left: 1px solid rgba(244, 244, 247, 1);
                    color: rgba(62, 95, 245, 1);
                }

                .log_ipt {
                    width: 70%;
                    height: 30px;
                    padding-left: 1em;
                    outline: none;
                    border: none;
                    border-radius: 10px;
                }
            }
        }

        .log_button {
            cursor: pointer;
            margin-top: 25px;
            text-align: center;
            height: 42px;
            line-height: 42px;
            background-color: #3e5ff5;
            color: #ffffff;
            text-align: center;
            font-weight: 800;
            border-radius: 5px;
        }
    }
}

.activetitle {
    font-weight: 800;
}

.log_iptc {
    width: 100%;
    height: 100%;
    border: #3e5ff5;
}
</style>
